<template>
  <div class="user-search default-radius" v-if="canQuery">
    <el-form
      :model="searchForm"
      ref="formRef"
      :label-width="searchConfig.labelWidth ?? '100px'"
      size="large"
    >
      <el-row :gutter="20">
        <template v-for="item in searchConfig.formItems" :key="item.prop">
          <el-col :span="item.span ?? 8">
            <el-form-item :label="item.label" :prop="item.prop">
              <template v-if="item.type === 'input'">
                <el-input v-model="searchForm[item.prop]" :placeholder="item.placeholder" />
              </template>
              <template v-if="item.type === 'date-picker'">
                <el-date-picker
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  v-model="searchForm[item.prop]"
                />
              </template>
              <template v-if="item.type === 'select'">
                <el-select
                  v-model="searchForm[item.prop]"
                  :placeholder="item.placeholder"
                  style="width: 100%"
                >
                  <template v-for="option in item.options" :key="option.value">
                    <el-option :label="option.label" :value="option.value" />
                  </template>
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <!-- 1.2.搜索按钮  -->
    <div class="btns">
      <el-button size="large" icon="Refresh" @click="handleResetClick">重置</el-button>
      <el-button size="large" icon="Search" type="primary" @click="handleQueryClick">
        查询
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import type { ISearchProps } from '@/components/page-search/type';
import usePermissions from '@/hooks/usePermissions';

const props = defineProps<ISearchProps>();
const formRef = ref<FormInstance>();

const canQuery = usePermissions(props.searchConfig.pageName + ':query');

const initialForm: any = {};
for (const item of props.searchConfig.formItems) {
  initialForm[item.prop] = item.defaultValue ?? '';
}
const searchForm = reactive(initialForm);

const emits = defineEmits(['queryClick', 'resetClick']);

function handleResetClick() {
  formRef.value?.resetFields();
  emits('resetClick');
}

function handleQueryClick() {
  emits('queryClick', searchForm);
}
</script>

<style scoped lang="scss">
.user-search {
  padding: 20px;
  background-color: #ffffff;

  .el-form {
    padding-top: 20px;
    padding-right: 10px;
  }

  .el-form-item {
    padding: 20px 40px;
    margin-bottom: 0;
  }

  .btns {
    text-align: right;
    padding: 0 50px 10px 0;
  }
}
</style>
